{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.ns-discount { display: flex; justify-content: space-between; height: 34px; line-height: 34px; padding: 5px 15px; background-color: #F6FBFD; border: 1px dashed #BCE8F1; }
	.ns-exchange-type {padding: 0 20px; position: relative;}
	.ns-exchange-type:hover {border: 1px solid #ff8143;}
	.ns-exchange-selected {border: 1px solid #ff8143;}
	.ns-exchange-selected:after {
		content: "";
		display: inline-block;
		width: 20px;
		height: 20px;
		background-image: url(__STATIC__/img/selected.png);
		position: absolute;
		bottom: 0;
		right: 0;
	}
</style>
{/block}
{block name="main"}
<div class="layui-collapse ns-tips">
	<div class="layui-colla-item">
		<h2 class="layui-colla-title">操作提示</h2>
		<ul class="layui-colla-content layui-show">
			<li>标识“<span class="required">*</span>”的选项为必填项，其余为选填项</li>
			<li>有效期类型可选固定时间和自领取之日起
				<p>1、固定时间：选择结束日期，所有领取的优惠券有效期都截止在结束日期当天</p>
				<p>2、自领取之日起：填写一个数字，表示从领取之日起有效期持续多少天</p>
			</li>
		</ul>
	</div>
</div>

<div class="layui-form ns-form">

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>优惠券名称：</label>
		<div class="layui-input-block">
			<input type="text" name="coupon_name" lay-verify="required" autocomplete="off" class="layui-input ns-len-long">
		</div>
	</div>

	<div class="layui-form">
		<div class="layui-form-item">
			<label class="layui-form-label">优惠券类型：</label>
			<div class="layui-input-block">
				<button class="layui-btn layui-btn-primary ns-exchange-type ns-exchange-selected" data-status="reward">满减</button>
				<button class="layui-btn layui-btn-primary ns-exchange-type" data-status="discount">折扣</button>
				<input type="hidden" name="type" value="reward">
			</div>
		</div>
	</div>

	<div class="layui-form-item" id="coupon_type">
		<label class="layui-form-label"><span class="required">*</span>优惠券面额：</label>
		<div class="layui-input-block">
			<div class="layui-input-inline">
				<input type="number" name="money" min="0" lay-verify="required|number|money" autocomplete="off" class="layui-input ns-len-short">
			</div>
			<span class="layui-form-mid">元</span>
		</div>
		<div class="ns-word-aux">
			<p>价格不能小于0，可保留两位小数</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>发放数量：</label>
		<div class="layui-input-block">
			<div class="layui-input-inline">
				<input type="number" name="count" min="0" lay-verify="required|number|int" autocomplete="off" class="layui-input ns-len-short">
			</div>
			<span class="layui-form-mid">张</span>
		</div>
		<div class="ns-word-aux">
			<p>发放数量必须大于0，且必须为整数</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>最大领取数量：</label>
		<div class="layui-input-block">
			<div class="layui-input-inline">
				<input type="number" name="max_fetch" min="0" value="1" lay-verify="required|number|int|max" autocomplete="off" class="layui-input ns-len-short">
			</div>
			<span class="layui-form-mid">张</span>
		</div>
		<div class="ns-word-aux">
			<p>数量不能小于0，且必须为整数；设置为0时，可无限领取</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>满多少元可以使用：</label>
		<div class="layui-input-block">
			<div class="layui-input-inline">
				<input type="number" name="at_least" min="0" lay-verify="required|number|money" autocomplete="off" class="layui-input ns-len-short">
			</div>
			<span class="layui-form-mid">元</span>
		</div>
		<div class="ns-word-aux">
			<p>价格不能小于0，无门槛请设为0</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label img-upload-lable">优惠券图片：</label>
		<div class="layui-input-block img-upload">
			<div class="upload-img-block">
				<div class="upload-img-box">
					<div class="ns-upload-default" id="couponImg">
						<div class="upload">
							<img src="SHOP_IMG/upload_img.png" />
							<p>点击上传</p>
						</div>
					</div>
					<div class="operation"  >
						<div >
							<i title="图片预览" class="iconfont iconreview js-preview" style="margin-right: 20px;"></i>
							<i title="删除图片" class="layui-icon layui-icon-delete js-delete" ></i>
						</div>
						<div class="replace_img js-replace">点击替换</div>
					</div>
					<input type="hidden" name="image" />
				</div>
				<!-- <p id="couponImg" class="no-replace">替换</p>
				<i class="del">x</i> -->
			</div>
		</div>
		<div class="ns-word-aux">
			<p>建议尺寸：325*95像素，图片上传默认不限制大小</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">是否允许直接领取：</label>
		<div class="layui-input-block">
			<input type="checkbox" name="is_show" lay-filter="" value="1" lay-skin="switch" checked />
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">有效期类型：</label>
		<div class="layui-input-block">
			<input type="radio" name="validity_type" value="0" lay-filter="filter" checked="checked" title="固定时间">
			<input type="radio" name="validity_type" value="1" lay-filter="filter" title="领取之日起">
		</div>
	</div>

	<div class="layui-form-item ns-end-time">
		<label class="layui-form-label">活动结束时间：</label>
		<div class="layui-input-block">
			<input type="text" name="end_time" lay-verify="time" id="end_time" class="layui-input ns-len-mid" autocomplete="off" readonly>
		</div>
	</div>

	<div class="layui-form-item ns-fixed-term layui-hide">
		<label class="layui-form-label">领取之日起：</label>
		<div class="layui-input-block">
			<div class="layui-input-inline">
				<input type="number" min="1" max="365" value="10" name="fixed_term" lay-verify="days" autocomplete="off" class="layui-input ns-len-short">
			</div>
			<span class="layui-form-mid">天有效</span>
		</div>
		<div class="ns-word-aux">
			<p>不能小于0，且必须为整数</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动商品：</label>
		<div class="layui-input-block">
			<input type="radio" name="goods_type" lay-filter="goods_type" value="1" title="全部商品参与" checked>
			<input type="radio" name="goods_type" lay-filter="goods_type" value="2" title="指定商品参与">
		</div>
	</div>

	<div class="layui-form-item goods_list" style="display:none">
		<label class="layui-form-label"></label>
		<div class="layui-input-block">

			<table id="selected_goods_list"></table>
			<button class="layui-btn ns-bg-color" onclick="addGoods()">选择商品</button>
		</div>
	</div>
	<input type="hidden" name="goods_ids">

	<div class="ns-form-row">
		<button class="layui-btn ns-bg-color" lay-submit lay-filter="save">保存</button>
		<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
	</div>
</div>

<!-- 操作 -->
<script type="text/html" id="operation">
	<div class="ns-table-btn">
		<a class="layui-btn" onclick="delGoods({{d.goods_id}})">删除</a>
	</div>
</script>
{/block}
{block name="script"}
<script>
    var submitRule, delRule;
    var goods_list = [], selectedGoodsId = [], goods_id=[],table;

    layui.use(['form', 'laydate','form'], function() {
        var form = layui.form,
            laydate = layui.laydate,
            repeat_flag = false; //防重复标识
        currentDate = new Date();  //当前时间
        form.render();

        currentDate.setDate(currentDate.getDate() + 10);  //10天后的日期

        // 时间模块
        laydate.render({
            elem: '#end_time', //指定元素
            type: 'datetime',
            value: currentDate
        });

        var upload = new Upload({
			elem: '#couponImg'
		});

        renderTable(goods_list); // 初始化表格

        //监听活动商品类型
        form.on('radio(goods_type)', function(data){
            var value = data.value;

            if(value == 1){
                $(".goods_list").hide();
            }
            if(value == 2){
                $(".goods_list").show();
            }
        });

        // 监听单选按钮
        form.on('radio(filter)', function(data) {
            if (data.value == 0) {
                $('.ns-end-time').removeClass('layui-hide');
                $('.ns-fixed-term').addClass('layui-hide');
            } else {
                $('.ns-fixed-term').removeClass('layui-hide');
                $('.ns-end-time').addClass('layui-hide');
            }
        });

        /**
         * 表单验证
         */
        form.verify({
            days: function(value) {
                if (value == '') {
                    return;
                }
                if (value%1 != 0) {
                    return '请输入整数';
                }
            },
            number: function (value) {
                if (value < 0) {
                    return '请输入大于或等于0的数!'
                }
            },
            int: function (value) {
                if (value%1 != 0) {
                    return '请输入整数!'
                }
                if (value < 0) {
                    return '请输入大于0的数!'
                }
            },
            money: function (value) {
                var arrMen = value.split(".");
                var val = 0;
                if (arrMen.length == 2) {
                    val = arrMen[1];
                }
                if (val.length > 2) {
                    return '保留小数点后两位'
                }
            },
            time: function(value) {
                var now_time = (new Date()).getTime();
                var end_time = (new Date(value)).getTime();
                if (now_time > end_time) {
                    return '结束时间不能小于当前时间!'
                }
            },
            max: function(value) {
                var _count = $("input[name=count]").val();
                if (parseFloat(value) > parseFloat(_count)) {
                    return '最大领取数量不能超过发放数量!';
                }
            },
            fl: function(value, item) {
                var str = $(item).parents(".layui-form-item").find("label").text().split("*").join("");
                str = str.substring(0, str.length - 1);

                if (value < 1) {
                    return str + "不能小于1折";
                }

                if (value > 9.9) {
                    return str + "不能大于9.9折";
                }

                var arrMen = value.split(".");
                var val = 0;
                if (arrMen.length == 2) {
                    val = arrMen[1];
                }
                if (val.length > 2) {
                    return str + "最多可保留两位小数";
                }
            }
        });

        /**
         * 监听提交
         */
        form.on('submit(save)', function(data) {

            if (data.field.is_show == undefined) {
                data.field.is_show = 0;
            }

            if(data.field.goods_type != 1){
                if(data.field.goods_ids == ''){
                    layer.msg("请选择商品");
                    return;
                }
            }

            if (repeat_flag) return;
            repeat_flag = true;

			// 删除图片
			if(!data.field.image) upload.delete();

            $.ajax({
                url: ns.url("coupon://shop/coupon/add"),
                data: data.field,
                dataType: 'JSON',
                type: 'POST',
                success: function(res) {
                    repeat_flag = false;

                    if (res.code == 0) {
                        layer.confirm('添加成功', {
							title:'操作提示',
                            btn: ['返回列表', '继续添加'],
							closeBtn: 0,
                            yes: function(){
                                location.href = ns.url("coupon://shop/coupon/lists")
                            },
                            btn2: function() {
                                location.href = ns.url("coupon://shop/coupon/add")
                            }
                        });
                    }else{
                        layer.msg(res.message);
                    }
                }
            });

        });

        submitRule = function() {
            var money = $("#money").val().trim(),
                discount_money = $("#discount_money").val().trim();

            if (Number(money) == "0" || Number(discount_money) == "0") {
                layer.msg("满减金额不能为空！", {icon: 5, anim: 6});
                return false;
            }
            if (Number(money) < 0 || Number(discount_money) < 0) {
                layer.msg("金额不能小于0！", {icon: 5, anim: 6});
                return false;
            }
            if (Number(money) * 100 % 1 != 0 || Number(discount_money) * 100 % 1 != 0) {
                layer.msg("金额最多保留小数点后两位！", {icon: 5, anim: 6});
                return false;
            }

            for (var i=0; i<$(".ns-discount-box .ns-discount").length; i++) {
                var money_num = $(".ns-discount-box .ns-discount").eq(i).find(".money-num").text();
                if (money == money_num) {
                    layer.msg("该金额规则已添加，不可重复添加！");
                    return false;
                }
            }

            var html = '<div class="ns-discount ns-form-row">'+
                '<div class="ns-discount-con">'+
                '<p>单笔订单满<span class="required money-num">' + money + '</span>元，立减现金<span class="required discount_money-num">' + discount_money + '</span>元</p>'+
                '</div>'+
                '<div class="ns-discount-del">'+
                '<button class="layui-btn ns-bg-color" onclick="delRule(this)">删除</button>'+
                '</div>'+
                '</div>';
            $(".ns-discount-box").append(html);
        };

        delRule = function(obj) {
            $(obj).parent().parent().remove();
        };

        $(".ns-exchange-type").click(function() {
            $(this).addClass("ns-exchange-selected");
            $(this).siblings("button").removeClass("ns-exchange-selected");

            var type = $(this).attr('data-status');

            var current_type = $("input[name='type']").val();
            if(current_type == type){
                return false;
            }

            $("input[name='type']").val(type);

            var html = '';
            if(type == 'reward'){
                html += '<label class="layui-form-label"><span class="required">*</span>优惠券面额：</label>' +
						'<div class="layui-input-block">' +
							'<div class="layui-input-inline">' +
								'<input type="number" name="money" min="0" lay-verify="required|number|money" autocomplete="off" class="layui-input ns-len-short">' +
							'</div>' +
							'<span class="layui-form-mid">元</span>' +
						'</div>' +
						'<div class="ns-word-aux">' +
							'<p>价格不能小于0，可保留两位小数</p>' +
						'</div>';

                $('.discount_limit').remove();
			}

            if(type == 'discount'){
                html += '<label class="layui-form-label"><span class="required">*</span>优惠券折扣：</label>' +
                    '<div class="layui-input-block">' +
                    '<div class="layui-input-inline">' +
                    '<input type="number" name="discount" min="1" lay-verify="required|fl" autocomplete="off" class="layui-input ns-len-short">' +
                    '</div>' +
                    '<span class="layui-form-mid">折</span>' +
                    '</div>' +
                    '<div class="ns-word-aux">' +
                    '<p>优惠券折扣不能小于1折，且不可大于9.9折，可保留两位小数</p>' +
                    '</div>';

		    	var discount_limit = '';
                discount_limit += '<div class="layui-form-item discount_limit">' +
                    '<label class="layui-form-label">最多优惠：</label>' +
                    '<div class="layui-input-block">' +
                    '<div class="layui-input-inline">' +
                    '<input type="number" name="discount_limit" min="0" lay-verify="number|int" autocomplete="off" class="layui-input ns-len-short">' +
                    '</div>' +
                    '<span class="layui-form-mid">元</span>' +
                    '</div>' +
                    '</div>';
                $('#coupon_type').after(discount_limit);
            }
			$('#coupon_type').html(html);
        });

    });

    // 表格渲染
    function renderTable(goods_list) {
        //展示已知数据
        table = new Table({
            elem: '#selected_goods_list',
            cols: [
                [{
                    field: 'goods_name',
                    title: '商品名称',
                    unresize: 'false',
                    width: '50%'
                }, {
                    field: 'price',
                    title: '商品价格(元)',
                    unresize: 'false',
                    align: 'right',
                    width: '20%',
                    templet: function(data) {
                        return '￥' + data.price;
                    }
                }, {
                    field: 'goods_stock',
                    title: '库存',
                    unresize: 'false',
                    align: 'center',
                    width: '20%'
                }, {
                    title: '操作',
                    toolbar: '#operation',
                    unresize: 'false',
                    width: '10%'
                }],
            ],
            data: goods_list,
        });
    }

    // 删除选中商品
    function delGoods(id) {
        var i, j;
        $.each(goods_list, function(index, item) {
            var goods_id = item.goods_id;

            if (id == Number(goods_id)) {
                i = index;
            }
        });
        goods_list.splice(i, 1);
        renderTable(goods_list);

        $.each(selectedGoodsId, function(index, item) {
            if (id == Number(item)) {
                j = index;
            }
        });
        selectedGoodsId.splice(j, 1);
        goods_id = selectedGoodsId;
        $("input[name='goods_ids']").val(goods_id.toString());
    }

    /* 商品 */
    function addGoods(){
        goodsSelect(function (res) {
			if (!res.length) return false;
            for(var i=0;i<res.length;i++) {
                goods_id.push(res[i].goods_id);
                goods_list.push(res[i]);
            }

            renderTable(goods_list);
            $("input[name='goods_ids']").val(goods_id.toString());
            selectedGoodsId = goods_id;

        },selectedGoodsId, {mode: "spu"});
    }

    function back() {
        location.href = ns.url("coupon://shop/coupon/lists");
    }
</script>
{/block}